package org.september.pisces.task.controller;

import org.september.pisces.task.entity.SimpleTask;
import org.september.pisces.task.enums.SimpleTaskStatus;
import org.september.pisces.task.service.DynamicScheduledTaskService;
import org.september.simpleweb.model.ResponseVo;
import org.september.smartdao.CommonDao;
import org.september.smartdao.model.Page;
import org.september.smartdao.model.ParamMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class TaskController {
	
	@Autowired
    private DynamicScheduledTaskService dynamicScheduledTaskService;
	
	@Autowired
	private CommonDao commonDao;
	
	public TaskController() {
		System.out.println("CacheController......");
	}
	@RequestMapping(List_Page)
	public ModelAndView taskList() throws Exception {
		ModelAndView mv = new ModelAndView();
		return mv;
	}
	
	@ResponseBody
    @RequestMapping(value = List_Data)
    public ResponseVo<Page<SimpleTask>> listTaskData(Page<SimpleTask> page ,String taskName) throws Exception {
		ParamMap pm  = new ParamMap();
		pm.put("taskName", taskName);
		page = commonDao.findPageByParams(SimpleTask.class, page, "SimpleTask.listTaskData", pm);
        return ResponseVo.<Page<SimpleTask>> BUILDER().setData(page).setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
    }
	
	@ResponseBody
    @RequestMapping(value = Pause_Action)
    public ResponseVo<String> pause(Long id) throws Exception {
		SimpleTask po = commonDao.get(SimpleTask.class, id);
		if(po!=null) {
			po.setRunStatus(SimpleTaskStatus.已暂停.id);
			commonDao.update(po);
		}
        return ResponseVo.<String> BUILDER().setData("success").setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
    }
	
	@ResponseBody
    @RequestMapping(value = Resume_Action)
    public ResponseVo<String> resume(Long id) throws Exception {
		SimpleTask po = commonDao.get(SimpleTask.class, id);
		if(po!=null) {
			po.setRunStatus(SimpleTaskStatus.待运行.id);
			commonDao.update(po);
		}
        return ResponseVo.<String> BUILDER().setData("success").setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
    }
	
	@ResponseBody
    @RequestMapping(value = "delete")
    public ResponseVo<String> delete(String taskName) throws Exception {
		//系统内置的不能删除
		dynamicScheduledTaskService.delete(taskName);
        return ResponseVo.<String> BUILDER().setData("success").setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
    }
	
	
	private static final String Mapping_Prefix = "/pisces/task";
	public static final String List_Page = Mapping_Prefix+"/taskList";
	public static final String List_Data = Mapping_Prefix+"/listTaskData";
	public static final String Pause_Action = Mapping_Prefix+"/pause";
	public static final String Resume_Action = Mapping_Prefix+"/resume";
}
